#!/usr/bin/env python

import os
import logging
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp


class Volunteer(db.Model):
  created     = db.DateProperty(auto_now_add=False)
  first_name  = db.StringProperty()
  last_name   = db.StringProperty()
  address     = db.PostalAddressProperty()
  country     = db.StringProperty()
  geopt       = db.GeoPtProperty()
  phone       = db.PhoneNumberProperty()
  email       = db.EmailProperty()

  def get_name(self):
    name = ''
    if self.first_name:
      name = name + self.first_name + ' '
    if self.last_name:
      name = name + self.last_name
    return name

  def get_address(self):
    addr = ''
    if self.address:
      addr = addr + self.address + ', '
    if self.country:
      addr = addr + self.country
    return addr


class VolunteersHandler(webapp.RequestHandler):

  def get(self):
    key = self.request.get('delete')
    if key:
      volunteer = Volunteer.get(key)
      volunteer.delete()

    self.redirect('/members')

  def post(self):
    volunteer = None
    key = self.request.get('key')
    if key:
      volunteer = Volunteer.get(key)
    else:
      volunteer = Volunteer()

    volunteer.first_name  = self.getValueOrNone('first_name')
    volunteer.last_name   = self.getValueOrNone('last_name')
    volunteer.address     = self.getValueOrNone('address')
    volunteer.country     = self.getValueOrNone('country')
    volunteer.geopt       = self.getValueOrNone('geopt')
    volunteer.phone       = self.getValueOrNone('phone')
    volunteer.email       = self.getValueOrNone('email')

    volunteer.put()

    self.redirect('/members')

  def getValueOrNone(self, property):
    value = self.request.get(property)
    if value:
      return value
    else:
      return None


def main():
  application = webapp.WSGIApplication([
      ('.*', VolunteersHandler),
    ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
